package com.ukao.steward.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.ukao.steward.bean.StringBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.retrofit.ApiCallback;
import com.ukao.steward.retrofit.ApiClient;
import com.ukao.steward.retrofit.ApiStores;
import com.ukao.steward.util.L;

import java.util.HashMap;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;


public class GpsUpdateService extends Service {
	private final IBinder mBinder = new GPSServiceBinder();



	public boolean flag = false;
	private AMapLocationClient mlocationClient;
	private AMapLocationClientOption locationOption;
	private CompositeSubscription mCompositeSubscription;

	public void startService() {
		initLocation();
	}
	private void initLocation(){

		//初始化client
		mlocationClient= new AMapLocationClient(this);
		locationOption= getDefaultOption();
		//设置定位参数
		mlocationClient.setLocationOption(locationOption);
		// 设置定位监听
		mlocationClient.setLocationListener(locationListener);
		mlocationClient.startLocation();
	}


	private AMapLocationClientOption getDefaultOption() {
		AMapLocationClientOption mOption = new AMapLocationClientOption();
		mOption.setGpsFirst(true);
		mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
		mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
		mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
		mOption.setInterval(300000);//可选，设置定位间隔。默认为2秒
		mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
		mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
		mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
		AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
		mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
		mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
		return mOption;
	}




	public void endService() {
		if (null != mlocationClient) {
			/**
			 * 如果AMapLocationClient是在当前Activity实例化的，
			 * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
			 */
			mlocationClient.onDestroy();
			mlocationClient = null;
			locationOption = null;
		}

	}


	@Override
	public IBinder onBind(Intent arg0) {

		return mBinder;
	}

	@Override
	public void onCreate() {

		startService();
		L.v("GPSService Started.");
	}

	@Override
	public void onDestroy() {

		onUnsubscribe();
		endService();
		L.v( "GPSService Ended.");
	}

	public class GPSServiceBinder extends Binder {
		public GpsUpdateService getService() {
			return GpsUpdateService.this;
		}
	}
	private int temp ;
	AMapLocationListener locationListener = new AMapLocationListener() {
		@Override
		public void onLocationChanged(final AMapLocation aMapLocation) {

			if (null != aMapLocation) {
				if (aMapLocation.getErrorCode() == 0) {
					if (temp == 0) {
						AddYWGPS(aMapLocation);
						temp++;

					}
				}


			}

		}

	};


	/**
	 * 添加移动轨迹
	 */
	public void AddYWGPS(AMapLocation location) {
		final HashMap mHashMap = new HashMap<String, String>();
		mHashMap.put("longitud",location.getLongitude()+"");
		mHashMap.put("latitude",location.getLatitude()+"");
		mHashMap.put("accessToken", SaveParams.getToken());
		L.i("AddYWGPS="+mHashMap.toString());
		addSubscription(apiStores().addYWGPS(Constant.createParameter(mHashMap)),
				new ApiCallback<StringBean>() {
					@Override
					public void onSuccess(StringBean model) {

						if (model.getHttpCode() == 200) {

						}else if (model.getHttpCode()==403||model.getHttpCode()==401){
							mlocationClient.stopLocation();
						}
					}


					@Override
					public void onFinish() {
						temp=0;

					}
				});



		}






	public ApiStores apiStores() {
		return ApiClient.retrofit().create(ApiStores.class);
	}


	public void onUnsubscribe() {
		//取消注册，以避免内存泄露
		if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions())
			mCompositeSubscription.unsubscribe();
	}


	public void addSubscription(Observable observable, Subscriber subscriber) {
		if (mCompositeSubscription == null) {
			mCompositeSubscription = new CompositeSubscription();
		}
		mCompositeSubscription.add(observable
				.subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(subscriber));
	}












}
